<?php

namespace app\admin\controller;

use app\common\facade\OssBackup;
use app\common\model\ContractBonusPool;
use app\common\model\ContractRelease;
use app\common\model\OrderTemporary;
use app\common\model\User;
use app\common\model\UserLevelLog;
use app\common\model\UserProductDiscount;
use think\facade\Cache;
use think\facade\View;
use app\common\model\Product;
use app\common\model\BonusPool;
use app\common\model\Area;
use app\common\model\Statistics;

class Test extends Base
{
    public function index()
    {
        $task = [
            /** 数据库备份 */
            [
                'title'  => 'OSS数据库备份-每日零点03分执行',
                'type'   => 'ossBackups',
                'record' => $this->getRecord('ossBackups')
            ],

            /** 数据统计 */
            [
                'title'  => '数据统计-每天凌晨00:02执行',
                'type'   => 'statistics',
                'record' => $this->getRecord('statistics')
            ]
        ];

        View::assign([
            'task' => $task
        ]);
        return View::fetch();
    }

    public function getRecord($type)
    {
        $list = Cache::get('task_' . $type);
        if (empty($list)) {
            return [];
        }
        $sort = [];
        foreach ($list as &$v) {
            $sort[] = $v['times'];
        }
        array_multisort($sort, SORT_DESC, $list);
        return $list;
    }

    public function execute()
    {
        try {
            $param = $this->request->post();
            $t1 = microtime(true);
            switch ($param['type']) {
                case "ossBackups":
                    $result = OssBackup::auto();
                    break;
                /** 数据统计 */
                case "statistics":
                    $result = Statistics::_timing();
                    break;
                default:
                    break;
            }
            if ($result['code'] == 1) {
                $msg = 'success';
            } else {
                $msg = 'error：' . $result['msg'];
            }
            $t2 = microtime(true);
            $data['admin'] = $this->admin['admin_name'];
            $data['times'] = time();
            $data['method'] = $this->request->action();
            $data['ip'] = $this->request->ip();
            $data['required'] = round($t2 - $t1, 6);
            $data['status'] = $msg;
            $list = Cache::get('task_' . $param['type']);
            $list[] = $data;
            Cache::set('task_' . $param['type'], $list);
            return json($result);
        } catch (\Exception $e) {
            return json(['code' => -1, 'msg' => $e->getMessage()]);
        }
    }
}

